﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MailServer.Server {
    [Serializable]
    public class Server {

        //private Information information;
        private string path;
        private Data data;

        public Server(string path) {
            //this.information = new Information(name, path);
            this.path = path;
            LoadData();
        }

        private void LoadData() {
            data = (Data)Persistence.Persistence.Deserealize(path);
            if(data == null)
                data = new Data();
        }

        public int GetMessageWaiting(string user) {
            LoadData();
            return data.GetMessageWaiting(user);
        }

        public List<Message.Message> GetNewMessages(string user) {
            LoadData();
            return data.GetNewMessages(user);
        }

        public Message.Message GetNextMessage(string user) {
            Message.Message message = data.GetNextMessage(user);
            Persist();
            return message;
        }

        public void Post(Message.Message message) {
            data.Post(message);
            Persist();
        }

        public void RemoveMessage(Message.Message message) {
            data.RemoveMessage(message);
            Persist();
        }

        public void CreateUser(string user) {
            data.AddUser(user);
            Persist();
        }

        public bool UserExists(string user) {
            LoadData();
            return data.ContainsUser(user);
        }

        public void RemoveUser(string user) {
            data.RemoveUser(user);
            Persist();
        }

        public List<string> ListUser() {
            LoadData();
            return data.ListUser();
        }

        private void Persist() {
            Persistence.Persistence.Serialize(data, path);
        }

    }
}
